<template>
  <div>
    <el-container>
      <el-header class="inside-header">
        <div>
          <!-- 面包屑 -->
          <el-breadcrumb separator=">">
            <el-breadcrumb-item>车辆备案</el-breadcrumb-item>
            <el-breadcrumb-item>场内车辆备案</el-breadcrumb-item>
            <el-breadcrumb-item class="breadcrumbColor">添加场内车辆备案</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </el-header>
      <el-main style="x">
        <el-form label-position="left" style="background: white; padding: 20px" :model="form" :rules="rules" ref="ruleFormRef"
          label-width="120px" scroll-to-error>
          <el-row>
            <el-col v-if="factoryId == 0" :span="9" >
              <el-form-item label="所属工厂"  prop="factory_id"
                            :rules="[{ required: true, message: '请选择所属工厂' }]">
                <el-select style="margin-left: 80px" v-model="form.factory_id" placeholder="请选择工厂" clearable>
                  <el-option v-for="fa in factory.factorys" :label="fa.factory_name" :key="fa.id" :value="fa.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="9">
              <el-form-item  label-width="200px" style="margin-left: -10px; margin-right: 10px"  label="环保等级编码内部管理号牌" prop="environmentalProtectionGrade">
                <el-input clearable style="width: 220px; margin-left: 10px" v-model="form.environmentalProtectionGrade" class="w-50 m-2" placeholder="请填写"/>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="车牌颜色">
                <el-select clearable v-model="form.licensePlateColor" placeholder="请选择" style="width: 220px">
                  <el-option label="蓝色" value="蓝色" />
                  <el-option label="绿色" value="绿色" />
                  <el-option label="白色" value="白色" />
                  <el-option label="黄色" value="黄色" />
                  <el-option label="黑色" value="黑色" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="车辆类型">
                    <el-input clearable style="width: 220px" v-model="form.vehicleType" class="w-50 m-2" placeholder="请填写"/>
               </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="9">
              <el-form-item label-width="200px" label="品牌型号">
                <el-input clearable style="width: 220px" v-model="form.brandModel" class="w-50 m-2" placeholder="请填写"/>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="发动机号码">
                <el-input clearable style="width: 220px" v-model="form.engineNumber" class="w-50 m-2" placeholder="请填写"/>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="注册日期">
                <el-date-picker clearable v-model="form.registrationDate" type="date" placeholder="请选择" style="width: 220px"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="9">
              <el-form-item label-width="200px" label="车辆识别代码">
                <el-input clearable style="width: 220px" v-model="form.vehicleIdentificationNumber" class="w-50 m-2" placeholder="请填写"/>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="排放阶段" prop="vehicleEmissions" style="margin-left: -10px; margin-right: 10px">
                <el-select clearable v-model="form.vehicleEmissions" style="width: 220px; margin-left: 10px" placeholder="请选择">
                  <el-option label="国0" value="国0" />
                  <el-option label="国Ⅰ" value="国Ⅰ" />
                  <el-option label="国Ⅱ" value="国Ⅱ" />
                  <el-option label="国Ⅲ" value="国Ⅲ" />
                  <el-option label="国Ⅳ" value="国Ⅳ" />
                  <el-option label="国Ⅴ" value="国Ⅴ" />
                  <el-option label="国Ⅵ" value="国Ⅵ" />
                  <el-option label="新能源" value="新能源" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="燃料类型">
                <el-select clearable v-model="form.vehicleFuel" style="width: 220px" placeholder="请选择">
                  <el-option label="汽油" value="汽油" />
                  <el-option label="柴油" value="柴油" />
                  <el-option label="电(以电能驱动的汽车)" value="电(以电能驱动的汽车)" />
                  <el-option label="混合油" value="混合油" />
                  <el-option label="天然气" value="天然气" />
                  <el-option label="液化石油气" value="液化石油气" />
                  <el-option label="甲醇" value="甲醇" />
                  <el-option label="乙醇" value="乙醇" />
                  <el-option label="太阳能" value="太阳能" />
                  <el-option label="混合动力" value="混合动力" />
                  <el-option label="氢" value="氢" />
                  <el-option label="生物燃料" value="生物燃料" />
                  <el-option label="无(限全挂车等无动力)" value="无(限全挂车等无动力)" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="9">
              <el-form-item label-width="200px" label="企业名称" style="margin-left:-10px;margin-right:10px" prop="enterpriseName">
                <el-input clearable style="width: 220px;margin-left:10px" v-model="form.enterpriseName" class="w-50 m-2" placeholder="请填写"/>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="使用性质">
                <el-select clearable v-model="form.natureOfVehicleUse" placeholder="请选择" style="width: 220px">
                  <el-option label="非营运" value="非营运" />
                  <el-option label="营转非" value="营转非" />
                  <el-option label="货运" value="货运" />
                  <el-option label="租赁" value="租赁" />
                  <el-option label="危险废物运输" value="危险废物运输" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item  label="所有人">
                <el-input clearable style="width: 220px" v-model="form.owner" class="w-50 m-2" placeholder="请填写"/>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label-width="200px" label="住址">
                <el-input clearable v-model="form.address" class="w-50 m-2" placeholder="请填写"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="9">
              <el-form-item label-width="200px" label="是否安装OBD" style="margin-left:-10px;margin-right:10px" prop="obdInstallation" >
                <el-select clearable v-model="form.obdInstallation" style="width: 220px;margin-left:10px" placeholder="请选择">
                  <el-option label="是" value="是" />
                  <el-option label="否" value="否" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="OBD安装日期">
                <el-date-picker clearable v-model="form.obdInstallationDate" type="date" placeholder="请选择"/>
              </el-form-item>
            </el-col>
          </el-row>
          <!--图片上传-->
           <el-row>
            <el-col :span="3" style="margin-left: 25px">
              <div class="UPtsxt"><span>行驶证正本</span></div>
                <el-upload v-model="form.drivingLicense" class="avatar-uploader" :file-list="state.fileListLicense"
                  action='#' :http-request="uploadAction" :limit="1" list-type="picture-card" accept="image/png,image/jpg,image/jpeg"
                 :on-remove="handleRemoveLicense" :on-preview="selectLicense" :class="{hide:showUploadLicense}">
                <el-icon class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
              </el-col>
            <el-col :span="3" style="margin-left: 25px">
              <div class="UPtsxt"><span>行驶证副本</span></div>
               <el-upload v-model="form.vehiclePhoto" class="avatar-uploader" :file-list="state.fileListPhoto"
                  action='#' :http-request="uploadvehiclePhoto" :limit="1" list-type="picture-card" accept="image/png,image/jpg,image/jpeg"
                  :on-remove="handleRemoveVehicle" :on-preview="selectV" :class="{hide:showUploadV}">
                <el-icon class="avatar-uploader-icon">
                   <Plus />
                </el-icon>
              </el-upload>
              </el-col>
                <el-col :span="3" style="margin-left: 25px">
                <div class="UPtsxt"><span>随车清单</span></div>
                <el-upload v-model="form.accompanyingList" class="avatar-uploader" :file-list="state.fileListACC"
                  action='#' :http-request="uploadAccompanyingList" :limit="1" list-type="picture-card" accept="image/png,image/jpg,image/jpeg"
                  :on-remove="handleRemoveAcc" :on-preview="handlePictureCardPreviewAcc" :class="{hide:showUpload}">
                  <el-icon class="avatar-uploader-icon">
                    <Plus />
                  </el-icon>
                </el-upload>
                </el-col>
               </el-row>
            <el-row>
              <el-col :span="20" style="margin: 40px 25px 20px">
               <el-tag class="ml-2" type="danger">图片操作为本地操作,点击添加、删除或预览图片,完成后提交上传数据。</el-tag>
            </el-col>
			      </el-row>
            <el-row :gutter="20">
             <div style="margin: 10px auto 20px">
               <el-col>
                  <el-button class="sele-but" @click="insert(form)">保存</el-button>
                <el-button class="empty-but" @click="close()">取消</el-button>
              </el-col>
            </div>
          </el-row>
        </el-form>
      </el-main>
    </el-container>
    	<!--行驶证正本查看图片-->
      <el-dialog v-model="drivingLicenseDig" >
        <el-image :src="form.drivingLicense" />
      </el-dialog>
       <!--行驶证副本查看图片-->
      <el-dialog v-model="vehiclePhotoDig" >
        <el-image :src="form.vehiclePhoto" />
      </el-dialog>
      <!--随车清单查看图片-->
      <el-dialog v-model="dialogVisible" >
        <el-image :src="form.accompanyingList" />
      </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref,onMounted } from "vue";
//接口
import { insertOnsite,uploadImg } from "@/api/mobilePollution";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import {v3ImgPreviewFn} from "v3-img-preview";
import {getFactoryInfo} from "../../../api/factory";
import { UploadProps } from "element-plus";
// 路由
import { useRouter } from "vue-router";
import moment from "moment";
onMounted(() => {
  getFactorys()
})
const router = useRouter();
const ruleFormRef = ref();
// 跳转回列表页
const close = () => {
  router.push({
    path: "/onsiteIndex",
  });
};
let factoryId = localStorage.getItem('factoryId')
let factory=reactive({factorys:[],factoryNames:{}});
const getFactorys = ()=>{
  getFactoryInfo({pageSize:1000}).then(res=>{
    let factorys = [];
    res.data?.list.forEach(e=>{
      factorys.push(e);
      factory.factoryNames[e.id]=e;
    })
    factory.factorys = factorys;
  })
}
//新增接口
const insert = () => {
  if (!form) return
  ruleFormRef.value.validate(valid=>{
    if (valid) {
        if(form.registrationDate){
          form.registrationDate = moment(form.registrationDate).format('YYYY-MM-DD')
        }else{
          form.registrationDate = ""
        }
        if(form.obdInstallationDate){
          form.obdInstallationDate = moment(form.obdInstallationDate).format('YYYY-MM-DD')
        }else{
          form.obdInstallationDate = ""
        }
        insertOnsite(form).then((res) => {
          if (res.code == 200) {
            ElMessage.success("保存数据成功");
            router.push({
              path: "/onsiteIndex",
            });
          } else {
            ElMessage.error("保存数据失败");
          }
        });
      }

  })
};
let form = reactive({ environmentalProtectionGrade: "" });
// 校验
const rules = {
  environmentalProtectionGrade: [
    {
      required: true,
      message: "请填写环保等级编码内部管理号牌",
      trigger: "blur",
    },
  ],
  enterpriseName:[{
      required: true,
      message: "请填写企业名称",
      trigger: "blur",
  }],
  obdInstallation:[{
    required: true,
    message: "请选择是否安装obd",
    trigger: "change",
  }],
  vehicleEmissions:[{
    required: true,
    message: "请选择排放阶段",
    trigger: "change",
  }]
};
//图片上传

const state = reactive({
  bannerUrl: '',
  fileList: [],
  fileName: '',
  fileListLicense:[],
  fileListPhoto:[],
  fileListACC:[]
})
const handleExceed = (files, fileList) => {
  if (state.fileList.length >= 1) {
    ElMessage.error('只能上传一个图片')
    return;
  }
}
const beforeUpload = (file) => {
  const type = ['image/jpeg', 'image/jpg', 'image/png']
  if (type.indexOf(file.type) === -1) {
    ElMessage.error('上传的文件必须是JPG、JPEG、PNG三种之一!')
    return false
  } else if (file.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
}
//行驶证正本
const  showUploadLicense = ref(false)
const drivingLicenseDig = ref(false)

const handleRemoveLicense= (uploadFile, uploadFiles) => {
  form.drivingLicense = null
  showUploadLicense.value = false
}
const selectLicense = (uploadFile) => {
  // form.drivingLicense = uploadFile.url
  // drivingLicenseDig.value = true
  v3ImgPreviewFn(uploadFile.url)
}
const uploadAction = (option) => {
  showUploadLicense.value = true
  let param = new FormData();
  param.append('files', option.file);
  uploadImg(param).then((res) => {
    if (res && res.code === 200) {
      form.drivingLicense = res.data[0]
      // state.fileList = []
      showUploadLicense.value = true
      ElMessage.success('上传成功！');
    }else {
      state.fileListLicense = []
      showUploadLicense.value = false
      ElMessage.error('上传失败,请重试');
    }
  })
}
//行驶证副本
const vehiclePhotoDig = ref(false)
const  showUploadV = ref(false)
const handleRemoveVehicle= (uploadFile, uploadFiles) => {
  form.vehiclePhoto = null
  showUploadV.value = false
}
const selectV = (uploadFile) => {
  // form.vehiclePhoto = uploadFile.url
  // vehiclePhotoDig.value = true
  v3ImgPreviewFn(uploadFile.url)
}
const uploadvehiclePhoto = (option) => {
  showUploadV.value = true
  let param = new FormData();
  param.append('files', option.file);
  uploadImg(param).then((res) => {
    if (res && res.code === 200) {
      form.vehiclePhoto = res.data[0]
      showUploadV.value = true
      // state.fileListPhoto = []
      ElMessage.success('上传成功！');
    }else {
      state.fileListPhoto = []
      showUploadV.value = false
      ElMessage.error('上传失败,请重试');
    }
  })
}
//随车清单（正面）
const dialogVisible = ref(false)
const  showUpload = ref(false)

const handleRemoveAcc= (uploadFile, uploadFiles) => {
  form.accompanyingList = null
  showUpload.value = false
}
const handlePictureCardPreviewAcc = (uploadFile) => {
  // form.accompanyingList = uploadFile.url
  // dialogVisible.value = true
  v3ImgPreviewFn(uploadFile.url)
}
const uploadAccompanyingList = (option) => {
  showUpload.value = true
  let param = new FormData();
  param.append('files', option.file);
  uploadImg(param).then((res) => {
    if (res && res.code === 200) {
      form.accompanyingList = res.data[0]
      // state.fileListACC = []
      showUpload.value = true
      ElMessage.success('上传成功！');
    }else {
      state.fileListACC = []
      showUpload.value = false
      ElMessage.error('上传失败,请重试');
    }
  })
}


// const imageUrl = ref('')
// 文件上传（照片）
// const handleAvatarSuccess = (response, uploadFile) => {
//   imageUrl.value = URL.createObjectURL();
// };


</script>
<style scoped>
/*超出限制 隐藏图片上传*/
::v-deep.hide .el-upload--picture-card {
  display: none;
}

/* 面包屑字体颜色更改 */

.breadcrumbColor >>> .el-breadcrumb__inner {
  color: #000;
}
/* 内部header */

.inside-header {
  height: 20px;
  display: flex;
  justify-content: left;
  align-items: flex-start;
  background:#f2f4f5
}
/* 横条蓝条样式 */

.head-bar {
  width: 100%;
  height: 40px;
  display: flex;
}

.head-bar-main {
  width: 3px;
  height: 20px;
  opacity: 1;
  background: #3780b9;
  margin-right: 11px;
}
/* 文件上传文字样式 */

.UPtsxt {
  width: 120px;
  height: 30px;
}
/* 文件上传样式 */
.avatar-img{
  width:120px;
  height:120px
}
.avatar-uploader {
  width: 120px;
  height: 120px;
  background-color: #e5f4ff;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #3780b9;
  width: 120px;
  height: 120px;
  text-align: center;
}
/* 空心按钮样式 */

.empty-but {
  border: 1px solid #3780b9;
  color: #3780b9;
}
/* 实心按钮背景样式 */

.sele-but {
  background: #3780b9;
  border: 0px;
  border-radius: 2px;
  color: white;
}
</style>
